import { defineStore } from 'pinia';
import { userApi } from '../api/user';
import type { LoginRequest, UserRegisterRequest, LoginResponse } from '../api/user';

interface UserState {
  token: string | null;
  user: {
    userId: string | null;
    customerId: string | null;
    username: string | null;
    isMerchant: boolean;
    merchantId: string | null;
    avatar: string | null;
  };
  loading: boolean;
  error: string | null;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: localStorage.getItem('token'),
    user: {
      userId: localStorage.getItem('userId'),
      customerId: localStorage.getItem('customerId'),
      username: localStorage.getItem('username'),
      isMerchant: localStorage.getItem('isMerchant') === 'true',
      merchantId: localStorage.getItem('merchantId'),
      avatar: localStorage.getItem('userAvatar'),
    },
    loading: false,
    error: null,
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    isMerchant: (state) => state.user.isMerchant,
    username: (state) => state.user.username || '未登录',
    avatar: (state) => state.user.avatar,
    userId: (state) => state.user.userId,
    customerId: (state) => state.user.customerId,
  },
  
  actions: {
    // 设置用户信息
    setUser(userData: LoginResponse) {
      console.log('Setting user data:', userData);
      
      this.token = userData.token;
      this.user.userId = userData.userId;
      this.user.customerId = userData.customerId;
      this.user.username = userData.username;
      this.user.isMerchant = userData.isMerchant;
      this.user.merchantId = userData.merchantId || null;
      this.user.avatar = userData.avatar || null;
      
      // 保存到本地存储
      localStorage.setItem('token', userData.token);
      localStorage.setItem('userId', userData.userId);
      localStorage.setItem('customerId', userData.customerId);
      localStorage.setItem('username', userData.username);
      localStorage.setItem('isMerchant', String(userData.isMerchant));
      if (userData.merchantId) {
        localStorage.setItem('merchantId', userData.merchantId);
      }
      if (userData.avatar) {
        localStorage.setItem('userAvatar', userData.avatar);
      }
    },
    
    // 清除用户信息
    clearUser() {
      console.log('Clearing user data');
      
      this.token = null;
      this.user.userId = null;
      this.user.customerId = null;
      this.user.username = null;
      this.user.isMerchant = false;
      this.user.merchantId = null;
      this.user.avatar = null;
      
      // 清除本地存储
      localStorage.removeItem('token');
      localStorage.removeItem('userId');
      localStorage.removeItem('customerId');
      localStorage.removeItem('username');
      localStorage.removeItem('isMerchant');
      localStorage.removeItem('merchantId');
      localStorage.removeItem('userAvatar');
    },
    
    // 用户登录
    async login(loginData: LoginRequest) {
      console.log('Login action called with:', loginData);
      this.loading = true;
      this.error = null;
      
      try {
        // 调用真实的登录API
        const response = loginData.isMerchantLogin
          ? await userApi.merchantLogin(loginData)
          : await userApi.login(loginData);
        
        if (response.code === 200 && response.data) {
          this.setUser(response.data);
          return true;
        } else {
          this.error = response.message || 'Login failed';
          return false;
        }
      } catch (error: any) {
        console.error('Login error:', error);
        this.error = error.message || 'Login error occurred';
        return false;
      } finally {
        this.loading = false;
      }
    },
    
    // 用户注册
    async register(userData: UserRegisterRequest) {
      console.log('Register action called with:', userData);
      this.loading = true;
      this.error = null;
      
      try {
        const response = userData.isMerchant
          ? await userApi.registerMerchant(userData)
          : await userApi.register(userData);
        
        if (response.code === 200) {
          return true;
        } else {
          this.error = response.message || 'Registration failed';
          return false;
        }
      } catch (error: any) {
        console.error('Registration error:', error);
        this.error = error.message || 'Registration error occurred';
        return false;
      } finally {
        this.loading = false;
      }
    },
    
    // 用户登出
    logout() {
      this.clearUser();
    }
  }
}); 